/**
 *
 * @author spider
 */
package br.unb.utils;

import java.awt.Component;
import java.awt.Color;
import java.io.PrintStream;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.JOptionPane;

public class Console {

    private static final DefaultStyledDocument document = new DefaultStyledDocument();
    static final StyleContext styles = new StyleContext();
    static final Style red = styles.addStyle("red", null);
    static final Style blue = styles.addStyle("blue", null);
    static final Style green = styles.addStyle("green", null);

    static {
        StyleConstants.setForeground(red, new Color(0x960000));
        StyleConstants.setForeground(blue, new Color(0x000096));
        StyleConstants.setForeground(green, new Color(0x009600));
        StyleConstants.setFontSize(red, 12);
        StyleConstants.setFontSize(blue, 12);
        StyleConstants.setFontSize(green, 12);
    }

    public static DefaultStyledDocument getDocument() {
        return document;
    }

    public synchronized static void println(String msg, PrintStream ps) {
        ps.println(
                Thread.currentThread().getName()
                + ": " + msg);
        try {
            document.insertString(
                    document.getLength(),
                    Thread.currentThread().getName() + ": " + msg + "\n",
                    ps.equals(System.err) ? red : blue);//Shared, must be synchornized?
        } catch (BadLocationException ex) {
            System.err.println("ERROR, bad location exception");
        }
    }

    public synchronized static void println(String msg, PrintStream ps, DefaultStyledDocument doc) {
        ps.println(
                Thread.currentThread().getName()
                + ": " + msg);
        if (doc != null) {
            try {
                doc.insertString(
                        doc.getLength(),
                        Thread.currentThread().getName() + ": " + msg + "\n",
                        ps.equals(System.err) ? red : blue);//Shared, must be synchornized?
            } catch (BadLocationException ex) {
                System.err.println("ERROR, bad location exception");
            }
        }
    }

    public static void println(String msg) {
        println(msg, System.out);
    }

    public static void printError(String msg) {
        println(msg, System.err);
    }

    public static void showMessageDialog(String message) {
        println(message, System.out);
        JOptionPane.showMessageDialog(null, message);
    }

    public static void showMessageDialog(Component parentComponent, Object message, String title, int messageType) {
        println(message.toString(), System.out);
        JOptionPane.showMessageDialog(parentComponent, message, title, messageType);
    }
}
